package com.example.newinfinity.MyViewModel

import android.app.Application
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.LiveData
import androidx.lifecycle.viewModelScope
import com.example.newinfinity.UserRoom.Repository
import com.example.newinfinity.UserRoom.User
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch

//AndroidViewModel是继承于ViewModel，两者均可以创建ViewModel
class UserViewModel(application: Application) : AndroidViewModel(application) {
    private val repository: Repository = Repository(application)

    fun insertUser(user: User) {
        viewModelScope.launch {
            repository.insertUser(user)
        }
    }

    fun updateUser(user: User) {
        viewModelScope.launch {
            repository.updateUser(user)
        }
    }

    suspend fun getCurrentLoginInUser(): User? {
        return repository.getCurrentLoginInUser()
    }

    suspend fun getUserByName(name: String, password: String): User? {
        return repository.getUserByName(name, password)
    }

    fun getAllUsers(): LiveData<List<User>>? {
        return repository.getAllUsers()
    }

    //退出当前的登录用户 提供给AccountPopupWindow()弹窗使用
    fun cancelLoginUser() {
        viewModelScope.launch(Dispatchers.IO) {
            val currentUser = getCurrentLoginInUser()
            if (currentUser != null) {
                currentUser.isLogin = false
                updateUser(currentUser)
            }
        }
    }

}